package com.yhd.filter;


import com.alibaba.fastjson.JSON;
import com.yhd.entity.dto.UserDto;
import com.yhd.entity.result.ResultVo;
import com.yhd.model.LoginUserModel;
import com.yhd.service.UserService;
import com.yhd.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return true;
        }
        String requestURI = request.getRequestURI();
        if (requestURI.contains("swagger")) return true;
        //判断session是否有
        LoginUserModel loginUserModel = (LoginUserModel) request.getSession().getAttribute("loginUserModel");
        if (loginUserModel != null) {
            return true;
        }
        String authToken = request.getHeader("auth-token");
        String authType = request.getHeader("auth-type");
        System.out.println("访问authToken："+authToken);
        System.out.println("访问authType："+authType);
        if (null != authToken && !"".equals(authToken) && null != authType && !"".equals(authType)){
            String userId = (String) redisUtils.get(authType + "-" + authToken);
            if (null != userId && !"".equals(userId)){
                UserDto user = userService.selectUserById(userId);
                if (null != user){
                    return true;
                }
            } else {
                return this.validateToken(response);
            }
        }
        //重置response
        response.reset();
        return this.validateToken(response);
    }

    /**
     * 校验过期Token
     * @param response
     * @return
     * @throws Exception
     */
    public boolean validateToken(HttpServletResponse response) throws Exception {
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(ResultVo.failure("10001","无访问权限，请先登录！")));
        pw.flush();
        pw.close();
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

